import { EditModal } from '@ycx/ui';
import { useTheme } from '@/store/settingsStore.ts';
import { App, Form, Input, Radio, Select } from 'antd';
import { Account } from '#/entity.ts';
import { useUserId } from '@/store/userStore.ts';
import { useMutation, useQuery } from '@tanstack/react-query';
import RoleServices from '@/api/services/roleServices.ts';
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import AccountServices from '@/api/services/accountServices.ts';
import { DefaultPwd } from '#/enmu.ts';
import { useCatch } from '@/hooks';
import { usePermissionsGuard } from '@/hooks';
import userServices from '@/api/services/userServices.ts';
import { canIUse, isValidPhone } from '@/utils';

export type EditUserModalRef = {
  open: (userId?: number) => void;
};

export type Props = {
  callback: () => void;
};

const EditUserModal = forwardRef<EditUserModalRef, Props>(({ callback }, ref) => {
  const { message } = App.useApp();
  const [userId, setUserId] = useState<number>();
  const [open, setOpen] = useState(false);

  const theme = useTheme();
  const [form] = Form.useForm<Account>();
  const id = useUserId();

  const catchFn = useCatch();
  const canAssign = usePermissionsGuard(['ACCOUNT_ASSIGN_ROLE']);

  const { data: roleOptions, isFetching: selectLoading } = useQuery({
    queryKey: ['role-list', id],
    queryFn: () => catchFn(() => RoleServices.getRolesByUserId({ userId: id! })),
    select: ({ data }) => data.map((i) => ({ label: i.roleName, value: i.id })),
  });

  const { data: accountData, isFetching } = useQuery({
    queryKey: ['account-detail', userId],
    queryFn: () => catchFn(() => AccountServices.getAccountById(userId!)),
    select: ({ data }) => {
      return {
        id: data.id,
        userName: data.userName,
        phone: data.phone,
        realName: data.realName,
        roleIds: data.roleList[0]?.id,
        userBlock: data.userBlock,
      } as Account;
    },
    enabled: !!userId,
    staleTime: 0,
  });

  useEffect(() => {
    if (accountData) form.setFieldsValue(accountData);
  }, [accountData, form]);

  const { data: companyOptions } = useQuery({
    queryKey: ['company-list'],
    queryFn: () => catchFn(() => userServices.getCompanyList()),
    select: ({ data }) => data.map((i) => ({ label: i.companyName, value: i.id })),
    enabled: id === 1,
  });

  const { mutateAsync: assignRole } = useMutation({
    mutationFn: AccountServices.assignRole,
  });

  const { mutate: create, isPending: createLoading } = useMutation({
    mutationFn: AccountServices.create,
    onSuccess: async ({ data }) => {
      const roleIds = form.getFieldValue('roleIds');
      if (roleIds && canAssign) {
        await assignRole({
          userId: data.id.toString(),
          roleIds: roleIds.toString(),
        });
      }
      message.success(`账号创建成功，初始密码为「${DefaultPwd.Gov}」`);
      close();
      callback();
    },
    onError: (error) => {
      message.error(error.message);
    },
  });

  const { mutate: update, isPending: updateLoading } = useMutation({
    mutationFn: AccountServices.update,
    onSuccess: async () => {
      const roleIds = form.getFieldValue('roleIds');
      if (roleIds && canAssign) {
        await assignRole({
          userId: userId!.toString(),
          roleIds: roleIds.toString(),
        });
      }
      message.success(`修改用户成功`);
      close();
      callback();
    },
    onError: (error) => {
      message.error(error.message);
    },
  });

  const handleSubmit = async () => {
    await form.validateFields();
    const data = form.getFieldsValue();
    if (id === 1) {
      const t = companyOptions?.find((i) => i.value.toString() === data.realName?.toString());
      data.companyId = t?.value;
      data.realName = t?.label;
    }
    if (userId) {
      update({ id: userId, ...data });
    } else {
      create(data);
    }
  };

  const close = () => {
    setOpen(false);
    setUserId(undefined);
    form.resetFields();
  };

  useImperativeHandle(ref, () => ({
    open: (userId?) => {
      setOpen(true);
      setUserId(userId);
    },
    close,
  }));

  return (
    <>
      <EditModal
        title={userId ? '修改用户' : '新增用户'}
        theme={theme}
        open={open}
        onClose={close}
        onCancel={close}
        forceRender
        loading={isFetching}
        confirmLoading={createLoading || updateLoading}
        onOk={handleSubmit}
        modalRender={(dom) => (
          <Form form={form} layout="vertical" initialValues={{ userBlock: false }}>
            {dom}
          </Form>
        )}
      >
        <Form.Item
          label="登录账号"
          name="userName"
          rules={[{ required: true, message: '请填写登录账号' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="电话号码"
          name="phone"
          rules={[
            {
              validator: (_r, value) => {
                return isValidPhone(value)
                  ? Promise.resolve()
                  : Promise.reject('请输入正确的手机号');
              },
            },
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="真实姓名"
          name="realName"
          rules={[{ required: true, message: '请填写真实姓名' }]}
        >
          {id === 1 ? <Select options={companyOptions ?? []} /> : <Input />}
        </Form.Item>
        <Form.Item label="角色" name="roleIds">
          <Select
            loading={selectLoading}
            options={roleOptions ?? []}
            disabled={!canIUse(['ACCOUNT_ASSIGN_ROLE'])}
          />
        </Form.Item>
        <Form.Item label="是否启用" name="userBlock" rules={[{ required: true }]}>
          <Radio.Group disabled={!userId}>
            <Radio value={false}>启用</Radio>
            <Radio value={true}>禁用</Radio>
          </Radio.Group>
        </Form.Item>
      </EditModal>
    </>
  );
});

export default EditUserModal;
